#include "UserRepository.h"
#include <QSqlQuery>
#include <QSqlError>

namespace UserManagementSystem {


UserRepository::UserRepository(const QString &db_path)
{
    m_db=QSqlDatabase::addDatabase("QSQLITE");

    m_db.setDatabaseName(db_path);

    if(!m_db.open()){
        qWarning() << "Database error:" << m_db.lastError().text();
        return;
    }
}

UserRepository::~UserRepository()
{
    //在析构函数中关闭数据库
    m_db.close();
}

void UserRepository::SetDBPath(const QString &db_path)
{
    m_db=QSqlDatabase::addDatabase("QSQLITE");

    m_db.setDatabaseName(db_path);

    if(!m_db.open()){
        qWarning() << "Database error:" << m_db.lastError().text();
        return;
    }
}

QList<PatientData> UserRepository::GetPatientData()
{
    LoadPatientDataFromDB();
    return m_patientData;
}

QList<CaseData> UserRepository::GetCaseDate()
{
    return m_caseDataLists;
}

void UserRepository::LoadPatientDataFromDB()
{
    if(m_db.isOpen()){
        //数据库是打开状态

        QSqlQuery query;
        query.exec("SELECT name,gender,birthday,phone,email,address,annotation,create_time,first_name,last_name FROM Patient");
        while(query.next()){
            PatientData person;
            person.name=query.value(0).toString();
            person.gender=query.value(1).toInt();
            person.birthday=query.value(2).toString();
            person.phone=query.value(3).toString();
            person.email=query.value(4).toString();
            person.address=query.value(5).toString();
            person.annotation=query.value(6).toString();
            person.create_time=query.value(7).toString();
            person.first_name=query.value(8).toString();
            person.lastname=query.value(9).toString();

            //年龄通过birthday计算,
            QString birth_year=person.birthday.left(4);
            m_patientData.push_back(person);
        }
        m_db.close();


    }
}

}
